package com.ruoyi.ax.service.impl;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.ax.domain.UserAssets;
import com.ruoyi.ax.mapper.UserAssetsMapper;
import com.ruoyi.ax.service.IUserAssetsService;
import com.ruoyi.common.core.domain.VModel;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 用户资源Service业务层处理
 *
 * @author AX
 * @date ${datetime}
 */
@Service
public class UserAssetsServiceImpl extends ServiceImpl<UserAssetsMapper, UserAssets> implements IUserAssetsService {
    @Autowired
    private UserAssetsMapper userAssetsMapper;

    /**
     * 查询用户资源
     *
     * @param id 用户资源主键
     * @return 用户资源
     */
    @Override
    public UserAssets selectUserAssetsById(Long id) {
        return userAssetsMapper.selectById(id);
    }

    /**
     * 查询用户资源列表
     *
     * @param userAssets 用户资源
     * @return 用户资源
     */
    @Override
    public List<UserAssets> selectUserAssetsList(UserAssets userAssets) {
        QueryWrapper<UserAssets> wrapper = new QueryWrapper<UserAssets>();
        wrapper.like(userAssets.getId() != null, "id", userAssets.getId());
        wrapper.like(userAssets.getUserId() != null, "user_id", userAssets.getUserId());
        return userAssetsMapper.selectList(wrapper);
    }

    /**
     * 新增用户资源
     *
     * @param userAssets 用户资源
     * @return 结果
     */

    @Override
    public int insertUserAssets(UserAssets userAssets) {
        userAssets.setCreateTime(DateUtils.getNowDate());
        return userAssetsMapper.insert(userAssets);
    }

    /**
     * 修改用户资源
     *
     * @param userAssets 用户资源
     * @return 结果
     */
    @Override
    public int updateUserAssets(UserAssets userAssets) {
        userAssets.setUpdateTime(DateUtils.getNowDate());
        return userAssetsMapper.updateById(userAssets);
    }

    /**
     * 批量删除用户资源
     *
     * @param idList 需要删除的用户资源主键
     * @return 结果
     */

    @Override
    public int deleteUserAssetsByIds(Long[] idList) {
        return userAssetsMapper.deleteBatchIds(Arrays.asList(idList));
    }

    /**
     * 加载所有用户资源
     *
     * @return 结果
     */
    @Override
    public List<UserAssets> loadAllUserAssets() {
        return userAssetsMapper.selectList(null);
    }

    /**
     * 创建多条数据
     *
     * @param userAssets
     * @return 结果
     */
    @Override
    public int bulkInsert(UserAssets[] userAssets) {
        int result = 0;
        for (UserAssets item : userAssets) {
            result += insertUserAssets(item);
        }
        return result;
    }

    /**
     * 通过excel导入数据
     *
     * @param files
     * @return
     */
    @Override
    public int importData(MultipartFile[] files) {

        int result = 0;
        MultipartFile file = files[0];
        if (null == file) return result;
        ExcelUtil<UserAssets> util = new ExcelUtil<UserAssets>(UserAssets.class);
        try {
            List<UserAssets> userAssetsList = util.importExcel(file.getInputStream());
            for (UserAssets userAssets : userAssetsList) {
                result += insertUserAssets(userAssets);
            }
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 更新属性，前端-后端-数据库三向绑定
     * 用于表格快速修改参数
     *
     * @param model
     * @return 结果
     */
    @Override
    public int updateAttr(VModel model) {
        UserAssets obj = new UserAssets();
        Optional<UserAssets> optionalUserAssets = Optional.of(obj);

        UserAssets userAssets = optionalUserAssets.get();
        userAssets.setId(Long.valueOf(model.getId()));
        try {
            Field field = UserAssets.class.getDeclaredField(model.getFieldName());
            field.setAccessible(true);
            field.set(userAssets, model.getModelValue());
            updateById(userAssets);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException("无法找到字段: " + model.getFieldName(), e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("无法访问字段: " + model.getFieldName(), e);
        }
        return 1;
    }

    /**
     * 获取用户主题相关信息
     * 取出时解码BASE64
     *
     * @return
     */
    @Override
    public Object getUserTheme() {
        Long userId = SecurityUtils.getUserId();
        QueryWrapper<UserAssets> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        UserAssets userAssets = userAssetsMapper.selectOne(wrapper);
        if (null == userAssets) {
            return null;
        }

        return JSON.parseObject(Base64.decode(userAssets.getThemeData()));
    }

    /**
     * 存入数据库，转成BASE64
     *
     * @param data
     * @return
     */
    @Override
    public int setUserTheme(String data) {
        Long userId = SecurityUtils.getUserId();
        QueryWrapper<UserAssets> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        UserAssets target = userAssetsMapper.selectOne(wrapper);

        if (null == target) {
            target = new UserAssets();
        }
        target.setUserId(userId);
        target.setThemeData(Base64.encode(data));
        return saveOrUpdate(target) ? 1 : 0;
    }
}
